import hashlib
import random
import requests
import time

# 请替换为你自己的 appKey 和 appSecret
appKey = '3952619c55de8131'
appSecret = 'dGBoSovBcx85jk9BoUmpOkYItwF2Eg6U'

def get_pronunciation(word):
    # 生成签名所需的随机数
    salt = str(random.randint(32768, 65536))
    # 构建签名
    sign_str = appKey + word + salt + appSecret
    sign = hashlib.md5(sign_str.encode()).hexdigest()
    # 有道 API 请求 URL
    url = 'https://openapi.youdao.com/api'
    # 请求参数
    params = {
        'q': word,
        'from': 'en',
        'to': 'zh-CHS',
        'appKey': appKey,
        'salt': salt,
        'sign': sign
    }
    try:
        # 发送请求
        response = requests.get(url, params=params)
        # 检查响应状态码
        response.raise_for_status()
        # 解析 JSON 响应
        result = response.json()
        print(result)
        # 检查是否有发音信息
        if 'basic' in result and 'us-speech' in result['basic']:
            us_pronunciation = result['basic']['us-speech']
            print(f"美式发音音频链接: {us_pronunciation}")
        if 'basic' in result and 'uk-speech' in result['basic']:
            uk_pronunciation = result['basic']['uk-speech']
            print(f"英式发音音频链接: {uk_pronunciation}")
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except KeyError:
        print("未找到发音信息")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    word = 'apple'
    get_pronunciation(word)